package com.icongyou.enterprise.talent_analysis.service.support;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Component //启用真实AI调用
public class OpenAIClient implements AIClient {

    @Value("${ai.api.key:}")
    private String apiKey;

    @Value("${ai.api.url:https://api.openai.com/v1/chat/completions}")
    private String apiUrl;

    @Value("${ai.model:gpt-3.5-turbo}")
    private String model;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String generateScoringStandard(String prompt) {
        return callAI(prompt, 1000);
    }

    @Override
    public String recommendMapping(String prompt) {
        return callAI(prompt, 500);
    }

    @Override
    public String evaluateDimension(String prompt) {
        return callAI(prompt, 50);
    }

    @Override
    public String analyzeText(String text, String analysisType) {
        String prompt = String.format("请对以下文本进行%s分析:\n\n%s", analysisType, text);
        return callAI(prompt, 200);
    }
    
    @Override
    public String extractKeywords(List<String> comments) {
        
        // 构建提示词
        StringBuilder promptBuilder = new StringBuilder();
        promptBuilder.append("请从以下教师评语中提取关键词并统计每个关键词的出现频次。\n\n");
        promptBuilder.append("要求：\n");
        promptBuilder.append("1. 提取能够反映学生特点的关键词（如：认真负责、代码规范、团队合作等）\n");
        promptBuilder.append("2. 统计每个关键词在所有评语中的出现次数\n");
        promptBuilder.append("3. 返回JSON格式：{\"关键词1\": 频次1, \"关键词2\": 频次2, ...}\n");
        promptBuilder.append("4. 只返回出现频次最高的前15个关键词\n\n");
        promptBuilder.append("教师评语列表：\n");
        
        for (int i = 0; i < comments.size(); i++) {
            promptBuilder.append(String.format("%d. %s\n", i + 1, comments.get(i)));
        }
        
        return callAI(promptBuilder.toString(), 500);
    }
    
    @Override
    public String chat(String prompt) {
        return callAI(prompt, 1000);
    }

    /**
     * 调用AI API的通用方法
     */
    private String callAI(String prompt, int maxTokens) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            Map<String, Object> requestBody = new HashMap<>();
            
            // 判断是否为通义千问（DashScope API）
            if (apiUrl.contains("dashscope.aliyuncs.com")) {
                // 通义千问格式
                requestBody.put("model", model);
                Map<String, Object> input = new HashMap<>();
                input.put("messages", List.of(
                    Map.of("role", "system", "content", "你是一个专业的人才评估专家,擅长分析学生学习数据并生成量化评分标准。"),
                    Map.of("role", "user", "content", prompt)
                ));
                requestBody.put("input", input);
                
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("result_format", "text");
                requestBody.put("parameters", parameters);
            } else {
                // OpenAI 标准格式
                requestBody.put("model", model);
                requestBody.put("messages", List.of(
                    Map.of("role", "system", "content", "你是一个专业的人才评估专家,擅长分析学生学习数据并生成量化评分标准。"),
                    Map.of("role", "user", "content", prompt)
                ));
                requestBody.put("max_tokens", maxTokens);
                requestBody.put("temperature", 0.7);
            }

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
            
            String response = restTemplate.postForObject(apiUrl, entity, String.class);
            
            // 解析响应
            JsonNode root = objectMapper.readTree(response);
            String content;
            
            if (apiUrl.contains("dashscope.aliyuncs.com")) {
                // 通义千问响应格式: output.text
                content = root.path("output").path("text").asText();
            } else {
                // OpenAI 响应格式: choices[0].message.content
                content = root.path("choices").get(0).path("message").path("content").asText();
            }
            
            return content;
            
        } catch (Exception e) {
            throw new RuntimeException("AI服务调用失败: " + e.getMessage(), e);
        }
    }
}
